<template>
  <div class="order-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>订单管理</h2>
    </div>

    <!-- 搜索和操作区 -->
    <div class="search-operation">
      <el-input
        v-model="searchParams.keyword"
        placeholder="请输入订单号/用户昵称搜索"
        clearable
        style="width: 300px; margin-right: 15px;"
        @keyup.enter="getOrderList"
      >
        <template #append>
          <el-button type="primary" @click="getOrderList">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </template>
      </el-input>
      
      <el-select
        v-model="searchParams.status"
        placeholder="订单状态"
        clearable
        style="width: 160px; margin-right: 15px;"
        @change="getOrderList"
      >
        <el-option label="全部" value=""></el-option>
        <el-option label="未完成" value="未完成"></el-option>
        <el-option label="已完成" value="已完成"></el-option>
        <el-option label="已取消" value="已取消"></el-option>
      </el-select>
      
      <el-date-picker
        v-model="searchParams.dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 300px;"
        @change="getOrderList"
      ></el-date-picker>
    </div>

    <!-- 订单列表 -->
    <el-table
      :data="orderList"
      border
      stripe
      size="mini"
      v-loading="loading"
      style="width: 100%; margin-top: 15px;"
    >
      <el-table-column prop="index" label="序号" width="80" align="center"></el-table-column>
      <el-table-column prop="orderNo" label="订单号" min-width="180"></el-table-column>
      <el-table-column prop="userNickname" label="用户昵称" min-width="120"></el-table-column>
      <el-table-column prop="consumptionItem" label="消费项目" min-width="120"></el-table-column>
      <el-table-column prop="orderAmount" label="订单金额" min-width="110" align="right">
        <template #default="scope">{{ formatCurrency(scope.row.orderAmount) }}</template>
      </el-table-column>
      <el-table-column prop="discountAmount" label="优惠金额" min-width="110" align="right">
        <template #default="scope">{{ formatCurrency(scope.row.discountAmount) }}</template>
      </el-table-column>
      <el-table-column prop="jiadaCoinDeduct" label="加达币抵扣" min-width="120" align="right">
        <template #default="scope">{{ scope.row.jiadaCoinDeduct }} 币</template>
      </el-table-column>
      <el-table-column prop="payAmount" label="支付金额" min-width="110" align="right">
        <template #default="scope">{{ formatCurrency(scope.row.payAmount) }}</template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态" min-width="110">
        <template #default="scope">
          <el-tag 
            :type="scope.row.orderStatus === '已完成' ? 'success' : 
                   scope.row.orderStatus === '已取消' ? 'danger' : 'warning'"
          >
            {{ scope.row.orderStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderTime" label="订单时间" min-width="160"></el-table-column>
      <el-table-column prop="completeTime" label="完成时间" min-width="160"></el-table-column>
      <el-table-column label="操作" min-width="300" align="center">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button 
              size="mini" 
              type="primary" 
              @click="handleViewDetail(scope.row)"
              icon="el-icon-view"
              class="operation-btn"
            >
              查看
            </el-button>
            <el-button 
              size="mini" 
              type="success" 
              @click="handleCompleteOrder(scope.row)"
              icon="el-icon-check"
              v-if="scope.row.orderStatus === '未完成'"
              class="operation-btn"
            >
              完成
            </el-button>
            <el-button 
              size="mini" 
              type="danger" 
              @click="handleCancelOrder(scope.row)"
              icon="el-icon-close"
              v-if="scope.row.orderStatus === '未完成'"
              class="operation-btn"
            >
              取消
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 15px;"
      />
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
      title="订单管理 / 订单信息"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <div class="order-detail">
        <!-- 订单状态 -->
        <div class="order-status" :class="orderStatusClass">
          {{ currentOrder.orderStatus || '未知状态' }}
        </div>
        
        <el-descriptions column="1" border :column="1" class="mt-4">
          <el-descriptions-item label="订单号">{{ currentOrder.orderNo || '-' }}</el-descriptions-item>
          <el-descriptions-item label="用户昵称">{{ currentOrder.userNickname || '-' }}</el-descriptions-item>
          <el-descriptions-item label="消费项目">{{ currentOrder.consumptionItem || '-' }}</el-descriptions-item>
          
          <el-descriptions-item label="费用信息">
            <el-table
              :data="feeDetails"
              border
              size="mini"
              style="width: 100%;"
            >
              <el-table-column prop="name" label="项目" width="160"></el-table-column>
              <el-table-column prop="value" label="金额" align="right"></el-table-column>
            </el-table>
          </el-descriptions-item>
          
          <el-descriptions-item label="下单时间">{{ currentOrder.orderTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ currentOrder.completeTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="订单备注">{{ currentOrder.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <el-button @click="dialogVisible = false">返回</el-button>
        <el-button type="primary" @click="handlePrint">打印</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

// 状态管理
const orderList = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const currentOrder = ref({});

// 搜索参数
const searchParams = reactive({
  keyword: '',
  status: '',
  dateRange: []
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 格式化金额
const formatCurrency = (value) => {
  return '¥' + parseFloat(value).toFixed(2);
};

// 订单状态样式
const orderStatusClass = computed(() => {
  switch(currentOrder.value.orderStatus) {
    case '未完成':
      return 'status-warning';
    case '已完成':
      return 'status-success';
    case '已取消':
      return 'status-danger';
    default:
      return '';
  }
});

// 费用详情数据
const feeDetails = computed(() => {
  return [
    { name: '订单金额', value: formatCurrency(currentOrder.value.orderAmount || 0) },
    { name: '优惠金额', value: formatCurrency(currentOrder.value.discountAmount || 0) },
    { name: '加达币抵扣', value: `${currentOrder.value.jiadaCoinDeduct || 0} 币` },
    { name: '实付金额', value: formatCurrency(currentOrder.value.payAmount || 0), isTotal: true }
  ];
});

// 获取订单列表
const getOrderList = () => {
  loading.value = true;
  
  // 模拟API请求
  setTimeout(() => {
    try {
      // 生成模拟数据
      const mockData = Array.from({ length: 56 }, (_, i) => {
        const baseAmount = 100 + Math.floor(Math.random() * 2000);
        const discountRate = 0.1 + Math.random() * 0.3;
        const discountAmount = Math.floor(baseAmount * discountRate);
        const jiadaCoinDeduct = Math.floor(Math.random() * 50);
        const payAmount = baseAmount - discountAmount - jiadaCoinDeduct;
        const statusOptions = ['未完成', '已完成', '已取消'];
        const status = statusOptions[Math.floor(Math.random() * (i % 5 === 0 ? 3 : 2))];
        const date = new Date();
        date.setDate(date.getDate() - Math.floor(Math.random() * 30));
        
        return {
          index: (pagination.currentPage - 1) * pagination.pageSize + i + 1,
          orderNo: `ORD${date.getTime().toString().slice(-8)}${i.toString().padStart(3, '0')}`,
          userNickname: i % 3 === 0 ? '' : `用户${Math.floor(Math.random() * 1000)}`,
          consumptionItem: ['汽车维修', '保养服务', '洗车', '配件更换', '检测'][Math.floor(Math.random() * 5)],
          orderAmount: baseAmount,
          discountAmount: discountAmount,
          jiadaCoinDeduct: jiadaCoinDeduct,
          payAmount: payAmount > 0 ? payAmount : 0,
          orderStatus: status,
          orderTime: date.toLocaleString('zh-CN'),
          completeTime: status === '已完成' ? new Date(date.getTime() + Math.random() * 86400000).toLocaleString('zh-CN') : '',
          remark: i % 4 === 0 ? '加急处理' : ''
        };
      });
      
      // 处理搜索过滤
      let filteredData = [...mockData];
      
      if (searchParams.keyword) {
        const keyword = searchParams.keyword.toLowerCase();
        filteredData = filteredData.filter(item => 
          item.orderNo.toLowerCase().includes(keyword) || 
          (item.userNickname && item.userNickname.toLowerCase().includes(keyword))
        );
      }
      
      if (searchParams.status) {
        filteredData = filteredData.filter(item => item.orderStatus === searchParams.status);
      }
      
      // 处理分页
      const startIndex = (pagination.currentPage - 1) * pagination.pageSize;
      const endIndex = startIndex + pagination.pageSize;
      
      orderList.value = filteredData.slice(startIndex, endIndex);
      pagination.total = filteredData.length;
    } catch (error) {
      ElMessage.error('获取订单列表失败，请重试');
      console.error('获取订单失败:', error);
    } finally {
      loading.value = false;
    }
  }, 800);
};

// 查看订单详情
const handleViewDetail = (row) => {
  currentOrder.value = { ...row };
  dialogVisible.value = true;
};

// 完成订单
const handleCompleteOrder = (row) => {
  ElMessageBox.confirm(
    `确定要将订单【${row.orderNo}】标记为已完成吗？`,
    '操作确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    row.orderStatus = '已完成';
    row.completeTime = new Date().toLocaleString('zh-CN');
    ElMessage.success('订单已标记为完成');
  }).catch(() => {
    // 取消操作
  });
};

// 取消订单
const handleCancelOrder = (row) => {
  ElMessageBox.confirm(
    `确定要取消订单【${row.orderNo}】吗？`,
    '操作确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    row.orderStatus = '已取消';
    ElMessage.success('订单已取消');
  }).catch(() => {
    // 取消操作
  });
};

// 打印订单
const handlePrint = () => {
  ElMessage.info('打印功能已触发，实际项目中会调用打印API');
  // 实际项目中可调用window.print()或专业打印组件
};

// 分页事件
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  getOrderList();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  getOrderList();
};

// 初始化加载数据
getOrderList();
</script>

<style scoped>
.order-management {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e5e7eb;
}

.search-operation {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.pagination-container {
  text-align: right;
}

.order-detail {
  padding: 10px 0;
}

.order-status {
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  padding: 10px 0;
}

.status-warning {
  color: #e6a23c;
}

.status-success {
  color: #67c23a;
}

.status-danger {
  color: #f56c6c;
}

::v-deep .el-descriptions__body {
  margin-top: 10px;
}

::v-deep .el-table .el-table__cell {
  padding: 8px 0;
}

/* 操作按钮样式优化 */
.operation-buttons {
  display: flex;
  gap: 8px; /* 按钮之间的间距 */
  justify-content: center;
}

.operation-btn {
  transition: all 0.2s ease-in-out; /* hover 动画过渡 */
}

.operation-btn:hover {
  transform: translateY(-2px); /* 轻微上浮效果 */
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1); /* 阴影增强立体感 */
}
</style>